package com.example.bloomfilterdemo;

import org.redisson.RedissonMultiLock;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA 2023.
 * Description:
 * User: homechen
 * Date: 2024-04-07
 * Time: 21:48
 */
@RestController
public class LockController {
    @Autowired
    private RedissonConfig redissonConfig;

    @GetMapping("/lock")
    public String lockResource() {
        String lockKey = "myLock"; // 设置锁名
        RLock rLock = redissonConfig.redissonConfig().getLock(lockKey);

        RLock lock = redissonConfig.redissonConfig().getFairLock(lockKey);  // 公平锁

        RReadWriteLock lock1 = redissonConfig.redissonConfig().getReadWriteLock(lockKey);
        lock1.readLock(); // 读锁
        lock1.writeLock(); //写锁

        RLock lock2 = redissonConfig.redissonConfig().getLock("lock1");
        RLock lock3 = redissonConfig.redissonConfig().getLock("lock2");
        RedissonMultiLock multiLock = new RedissonMultiLock(lock2, lock3);
        try {
            if (multiLock.tryLock()) {
                // 一次性获取所有的锁成功
            }
        } finally {
            multiLock.unlock(); // 释放所有的锁
        }

        // 此时去获取锁
        try {
            boolean isLocked = rLock.tryLock(30, TimeUnit.SECONDS);
            if (isLocked) {
                // 此时获取到锁
                try {
                    // 执行业务逻辑
                    TimeUnit.SECONDS.sleep(5);
                    return "成功获取锁，并成功执行任务！";
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    rLock.unlock(); // 进行释放锁
                }
            } else {
                return "获取锁失败！";
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "获取锁成功！";
    }
}
